package com.awesome.common.util.activityresultutil;

import android.content.Intent;

import androidx.fragment.app.FragmentManager;

/**
 * Description:启动需要接收返回结果的 Activity 的工具类
 * Created by 禽兽先生
 * Created on 2018/4/18
 */

public class ActivityResultUtil {
    private static final int REQUEST_CODE = 200;

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/12/16 10:18
     * Description:重载 {@link #startActivityForResult(FragmentManager, Intent, int, OnActivityResultCallBack)},默认 requestCode 为 200
     */
    public static void startActivityForResult(FragmentManager fragmentManager, Intent intent, OnActivityResultCallBack onActivityResultCallBack) {
        startActivityForResult(fragmentManager, intent, REQUEST_CODE, onActivityResultCallBack);
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/12/16 10:19
     * Description:使用自己的 intent(可以传参),启动 Activity 并等待返回值
     *
     * @param fragmentManager
     * @param intent                   自定义 intent
     * @param requestCode              请求码
     * @param onActivityResultCallBack 结果回调
     */
    public static void startActivityForResult(FragmentManager fragmentManager, Intent intent, int requestCode, OnActivityResultCallBack onActivityResultCallBack) {
        ActivityResultFragment activityResultFragment = (ActivityResultFragment) fragmentManager.findFragmentByTag(ActivityResultFragment.class.getSimpleName());
        if (activityResultFragment == null) {
            activityResultFragment = new ActivityResultFragment();
            fragmentManager.beginTransaction()
                    .add(activityResultFragment, ActivityResultFragment.class.getSimpleName())
                    .commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        activityResultFragment.startActivityForResult(intent, requestCode, onActivityResultCallBack);
    }
}
